/**
 * 文件：activity_sample_list.java
 * 包名：com.ronri.ams.sample;   --- 正式发布时需要修正
 * 说明：样品信息列表
 * 作者：MS During
 * 日期：2017/5/9
 * 历史：
 */
package com.ronri.ams.sample;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.adapter.ChoiceViewAdapter;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.PhotosBean;
import com.ronri.ams.bean.SampleBean;
import com.ronri.ams.bean.sample_info;
import com.ronri.ams.bean.template;
import com.ronri.common.UrlEncode;
import com.ronri.common.WaitDialog;
import com.ronri.db.LocalDataService;
import com.ronri.db.RemoteDataService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cz.nongyetongv5.application.InitApplication.LoginInfo;
import static com.cz.nongyetongv5.application.InitApplication.gSampleInfo;


public class activity_sample_list extends abstract_activity {

    // 本地数据库
    private LocalDataService mLocalDB = null;

    // 类别组件
    private ListView mlistView = null;

    private Context mContext = null;

    private int mBreedId = 0;
    private String mBreedName = null;
    private template mTemplate = null;

    // 删除
    private TextView mbtDelete = null;

    // 全选
    private TextView mbtSelectAll = null;

    // 列表数据
    private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();
    /**
     * name : 蔬菜
     * barcode : 2000001
     * num : 1
     * base : 1G
     * address : 常州
     * source : 123
     * memo : adsfa
     * photos : [{"PhotoPath":"aadfasd","Latitude":0,"Longitude":0,"Address":"","PhotoDate":"2017-05-15","Url":"","isUpload":false,"isOperator":false}]
     */

    private String name;
    private String barcode;
    private int num;
    private String base;
    private String address;
    private String source;
    private String memo;
    private List<PhotosBean> photos;

    private ChoiceViewAdapter mAdapter = null;

    /****
     * 创建视图
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample_list);
        Log.i("aaa","activity_sample_list");
        mContext = this;

        // 获取列表控件
        mlistView = (ListView) findViewById(R.id.list_sample);
        Bundle bundle = getIntent().getExtras();

        String szTitle = bundle.getString("title");
        String szvTitle = bundle.getString("vtitle");

//        String szSamples = bundle.getString("data");
//
//        // 生成结果
//        List<SampleBean> lObject = JSONArray.parseArray(szSamples, SampleBean.class);

        if (gSampleInfo.getSample_breed() != null) {
            for (sample_info.SampleBreedBean iTem : gSampleInfo.getSample_breed()) {
                Map<String, Object> ii = new HashMap<String, Object>();
                ii.put("listTitle", iTem.getBar_code() + "[" + iTem.getBreed_byname() + "]");
                ii.put("listData", ii);
                mItems.add(ii);
            }
        }

        // 设置标题
        setTitle(szTitle, szvTitle);

        // 初始化
        init();

        mAdapter = new ChoiceViewAdapter(this, mItems);
        mlistView.setAdapter(mAdapter);
        mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i < gSampleInfo.getSample_breed().size()) {

                    // 判断是否为定性
                    if(gSampleInfo.getNature() == 1){

                        Intent intent = new Intent(getApplication(), activity_add_dinxing_sample.class);

                        Bundle bund = new Bundle();
                        bund.putInt("point", gSampleInfo.getSample_breed().size() - 1);
                        bund.putString("title", "添加样品");
                        bund.putString("vtitle", "确定");

                        intent.putExtras(bund);

                        startActivityForResult(intent, SystemEnvironmental.Sample_Edit_Result);

                    }else {// 定量
                        switch (gSampleInfo.getSample_breed().get(i).getTemplate_id()) {
                            case "1": {
                                Intent intent = new Intent(getApplication(), activity_add_sample.class);

                                Bundle bund = new Bundle();
                                bund.putInt("point", gSampleInfo.getSample_breed().size() - 1);
                                bund.putString("title", "添加样品");
                                bund.putString("vtitle", "确定");

                                intent.putExtras(bund);

                                startActivityForResult(intent, SystemEnvironmental.Sample_Edit_Result);
                            }
                            break;
                            case "2": {
                                Intent intent = new Intent(getApplication(), activity_add_anim_sample.class);

                                Bundle bund = new Bundle();

                                bund.putString("title", "添加样品");
                                bund.putString("vtitle", "确定");

                                intent.putExtras(bund);

                                startActivityForResult(intent, SystemEnvironmental.Sample_Edit_Result);
                            }
                            break;
                            case "3":
                                Intent intent = new Intent(getApplication(), activity_add_milk_sample.class);

                                Bundle bund = new Bundle();

                                bund.putString("title", "添加样品");
                                bund.putString("vtitle", "确定");

                                intent.putExtras(bund);

                                startActivityForResult(intent, SystemEnvironmental.Sample_Edit_Result);
                                break;
                            case "4":
                                break;
                        }
                    }

                }
//
//                String szJson = (String) mItems.get(i).get("listData");
//
//                if (szJson != null) {
//                    SampleBean sample = JSON.parseObject(szJson, SampleBean.class);
//
//                    if (sample.getStype() == 0) {
//                        Intent intent = new Intent(getApplication(), activity_add_sample.class);
//                        Bundle bund = new Bundle();
//                        bund.putString("data", szJson);
//                        bund.putString("title", "添加样品");
//                        bund.putString("vtitle", "确定");
//
//                        intent.putExtras(bund);
//
//                        startActivityForResult(intent, SystemEnvironmental.Sample_Edit_Result);
//                    } else {
//                        Intent intent = new Intent(getApplication(), activity_add_sample.class);
//                        Bundle bund = new Bundle();
//                        bund.putString("data", szJson);
//                        bund.putString("title", "添加样品");
//                        bund.putString("vtitle", "确定");
//
//                        intent.putExtras(bund);
//
//                        startActivityForResult(intent, SystemEnvironmental.Sample_Edit_Result);
//                    }
//
//
//                }
            }
        });
    }

    @Override
    public boolean CancelReturn() {

        Intent intent = new Intent();
        Bundle bundle = new Bundle();

        bundle.putString("returnValue", "");

        intent.putExtras(bundle);

        setResult(RESULT_OK, intent);

        return super.CancelReturn();
    }

    /***
     * 选择新增的样品
     *
     * @return
     */
    @Override
    public boolean SureReturn() {
        // 弹框选择样品
        Intent intent = new Intent(getApplicationContext(), activity_select_breed.class);
        Bundle bundle = new Bundle();

        /*** 设置远程地址 ***/
        bundle.putString("remoteAddress", getResources().getString(R.string.remote_get_sample_worker));
        bundle.putString("filterKeyName", "breed_name");
        bundle.putString("viewTitleName", "breed_name");
        bundle.putInt("control_id", 0);
        bundle.putInt("selectMode", ListView.CHOICE_MODE_SINGLE);
        bundle.putString("title", "选择样品");
        bundle.putString("vtitle", "确认");

        intent.putExtras(bundle);

        // 启动选择样品
        startActivityForResult(intent, SystemEnvironmental.Sample_Select_Result);


        return false;
    }

    /***
     * 接收反馈动作
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SystemEnvironmental.Sample_Select_Result: {
                    if (data != null) {
                        Bundle bundle = data.getExtras();

                        String szJson = bundle.getString("returnValue");

                        JSONArray jsonArray = JSON.parseArray(szJson);

                        if (gSampleInfo.getNature() == 1){
                            if (jsonArray.size() > 0) {
                                JSONObject object = jsonArray.getJSONObject(0);
                                if (object != null) {
                                    mBreedName = object.getString("breed_name");
                                    mBreedId = object.getInteger("breed_id");

                                    Intent intent = new Intent(getApplication(), activity_add_dinxing_sample.class);

                                    Bundle bund = new Bundle();

                                    SampleBean sample = new SampleBean();

                                    sample.setId(-1);
                                    sample.setName(mBreedName);
                                    sample_info.SampleBreedBean sbean = new sample_info.SampleBreedBean();
                                    sbean.setCreate_user(LoginInfo.getData().getUser_id());
                                    sbean.setBreed_byname(mBreedName);
                                    sbean.setBreed_id(mBreedId);
                                    sbean.setTemplate_id("1");

                                    if (gSampleInfo.getSample_breed() == null)
                                        gSampleInfo.setSample_breed(new ArrayList<sample_info.SampleBreedBean>());

                                    gSampleInfo.getSample_breed().add(sbean);
                                    // String szSampleJson = JSONObject.toJSONString(sample);

                                    bund.putInt("point", gSampleInfo.getSample_breed().size() - 1);

                                    // bund.putString("data", szSampleJson);
                                    bund.putString("title", "添加样品");
                                    bund.putString("vtitle", "确定");

                                    intent.putExtras(bund);

                                    startActivityForResult(intent, SystemEnvironmental.Sample_New_Result);
                                }
                            }
                        }else {
                            if (jsonArray.size() > 0) {
                                JSONObject object = jsonArray.getJSONObject(0);
                                if (object != null) {
                                    mBreedName = object.getString("breed_name");
                                    mBreedId = object.getInteger("breed_id");
                                    getRemoteData(mBreedId);
                                }
                            }
                        }
                    }
                }
                break;
                case SystemEnvironmental.Sample_Edit_Result: {
                    // 更新列表
                    if (data != null) {
                        Bundle bundle = data.getExtras();

                        Map<String, Object> obj = new HashMap<String, Object>();

                        int npoint = bundle.getInt("point");
                        // 判断是否删除
                        if (bundle.containsKey("delete")){
                            gSampleInfo.getSample_breed().remove(npoint);
                            mItems.remove(npoint);
                            mAdapter.notifyDataSetChanged();
                        }else {
                            mItems.get(npoint).put("listTitle", gSampleInfo.getSample_breed().get(npoint).getBar_code() + "[" + gSampleInfo.getSample_breed().get(npoint).getBreed_byname() + "]");
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }
                break;
                case SystemEnvironmental.Sample_New_Result: {
                    // 更新列表
                    if (data != null) {
                        Bundle bundle = data.getExtras();
                        int npoint = bundle.getInt("point");

                        // 判断是否删除
                        if (bundle.containsKey("delete")){
                            gSampleInfo.getSample_breed().remove(npoint);
                        }else {
                            Map<String, Object> obj = new HashMap<String, Object>();

                            obj.put("listTitle", gSampleInfo.getSample_breed().get(npoint).getBar_code() + "[" + gSampleInfo.getSample_breed().get(npoint).getBreed_byname() + "]");

                            mItems.add(obj);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }
                break;
            }
        }else{
            switch (requestCode) {
                case SystemEnvironmental.Sample_New_Result: {
                    // 更新列表
                    if (data != null) {
                        Bundle bundle = data.getExtras();
                        int npoint = bundle.getInt("point");
                        gSampleInfo.getSample_breed().remove(npoint);
                    }
                }
                break;
            }
        }
    }

    /****
     * 获取远程数据
     */
    public void getRemoteData(int breedid) {

        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getBreedTemplate().getAddress());

        Map<String, Object> mParam = new HashMap<String, Object>();

        try {
            mParam.put("addFrom", 1);
            mParam.put("addMark", "android");
            mParam.put("page", 1);
            mParam.put("pageSize", 10);
            mParam.put("breed_id", breedid);
        } catch (Exception ex) {

        }

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getTdetail().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
                        if (szString.isEmpty())
                            return;

                        try {
                            mTemplate = JSON.parseObject(szString, template.class);

                            if (mTemplate.isSuccess()) {
                                switch (mTemplate.getData().getTemplate_id()) {
                                    case 1: {
                                        Intent intent = new Intent(getApplication(), activity_add_sample.class);

                                        Bundle bund = new Bundle();

                                        SampleBean sample = new SampleBean();

                                        sample.setId(-1);
                                        sample.setName(mBreedName);
                                        sample_info.SampleBreedBean sbean = new sample_info.SampleBreedBean();
                                        sbean.setCreate_user(LoginInfo.getData().getUser_id());
                                        sbean.setBreed_byname(mBreedName);
                                        sbean.setBreed_id(mBreedId);
                                        sbean.setTemplate_id("1");

                                        if (gSampleInfo.getSample_breed() == null)
                                            gSampleInfo.setSample_breed(new ArrayList<sample_info.SampleBreedBean>());

                                        gSampleInfo.getSample_breed().add(sbean);
                                        // String szSampleJson = JSONObject.toJSONString(sample);

                                        bund.putInt("point", gSampleInfo.getSample_breed().size() - 1);

                                        // bund.putString("data", szSampleJson);
                                        bund.putString("title", "添加样品");
                                        bund.putString("vtitle", "确定");

                                        intent.putExtras(bund);

                                        startActivityForResult(intent, SystemEnvironmental.Sample_New_Result);
                                    }
                                    break;
                                    case 2: {
                                        Intent intent = new Intent(getApplication(), activity_add_anim_sample.class);

                                        Bundle bund = new Bundle();

                                        SampleBean sample = new SampleBean();

                                        sample.setId(-1);
                                        sample.setName(mBreedName);

                                        sample_info.SampleBreedBean sbean = new sample_info.SampleBreedBean();
                                        sbean.setCreate_user(LoginInfo.getData().getUser_id());
                                        sbean.setBreed_byname(mBreedName);
                                        sbean.setBreed_id(mBreedId);
                                        sbean.setTemplate_id("2");

                                        String szSampleJson = JSONObject.toJSONString(sample);

                                        if (gSampleInfo.getSample_breed() == null)
                                            gSampleInfo.setSample_breed(new ArrayList<sample_info.SampleBreedBean>());

                                        gSampleInfo.getSample_breed().add(sbean);
                                        // String szSampleJson = JSONObject.toJSONString(sample);

                                        bund.putInt("point", gSampleInfo.getSample_breed().size() - 1);
                                        bund.putString("data", szSampleJson);
                                        bund.putString("title", "添加样品");
                                        bund.putString("vtitle", "确定");

                                        intent.putExtras(bund);

                                        startActivityForResult(intent, SystemEnvironmental.Sample_New_Result);
                                    }
                                    break;
                                    case 3:
                                        Intent intent = new Intent(getApplication(), activity_add_milk_sample.class);

                                        Bundle bund = new Bundle();

                                        SampleBean sample = new SampleBean();

                                        sample.setId(-1);
                                        sample.setName(mBreedName);

                                        sample_info.SampleBreedBean sbean = new sample_info.SampleBreedBean();
                                        sbean.setCreate_user(LoginInfo.getData().getUser_id());
                                        sbean.setBreed_byname(mBreedName);
                                        sbean.setBreed_id(mBreedId);
                                        sbean.setTemplate_id("3");

                                        String szSampleJson = JSONObject.toJSONString(sample);

                                        if (gSampleInfo.getSample_breed() == null)
                                            gSampleInfo.setSample_breed(new ArrayList<sample_info.SampleBreedBean>());

                                        gSampleInfo.getSample_breed().add(sbean);

                                        bund.putInt("point", gSampleInfo.getSample_breed().size() - 1);
                                        bund.putString("data", szSampleJson);
                                        bund.putString("title", "添加样品");
                                        bund.putString("vtitle", "确定");

                                        intent.putExtras(bund);

                                        startActivityForResult(intent, SystemEnvironmental.Sample_New_Result);
                                        break;
                                    case 4:
                                        break;
                                }
                            }
                        } catch (Exception ex) {

                        }
                    }

                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                            WaitDialog.ShowDialog(mContext, "请稍后...");
                        } else {
                            WaitDialog.HideDialog();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }
}
